//
//  StringExt.swift
//  test-ios
//
//  Created by wyz5204 on 2023/6/6.
//

import Foundation
import UIKit

//MARK: String
extension String {
    /// 字符串生成颜色
    var hexColor: UIColor {
        let hexString = self.trimmingCharacters(in: .whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        
        if hexString.hasPrefix("#") {
            
            scanner.locale = 1
        }
        
        var color: UInt64 = 0
        scanner.scanHexInt64(&color)
        
        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        
        return UIColor(red: red, green: green, blue: blue, alpha: 1)
    }
    
    /// 字符串生成 image
    var glImage: UIImage? {
        return UIImage.init(named: self)
    }
    
    /// 获取字符串 size
    /// - Parameters:
    ///   - font: 字体大小
    func getTextSize(font:UIFont) -> CGSize {
        let size = CGSize.init(width: SCREEN_WIDTH, height:  CGFloat(MAXFLOAT))
        let dic = [NSAttributedString.Key.font:font]
        let strSize = self.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context:nil).size
        return strSize
    }
    
    /// 字符串 转 控制器
    func vcFromString()-> UIViewController? {
        //获取命名空间也就是项目名称
        guard let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {return nil}
        
        //拼接
        let className=clsName + "." + self
        
        /// 字符串转Class
        guard let classT = NSClassFromString(className) else {return nil}
        //需要注意的是这里的`UIViewController`强转必须带上`.Type`,否则转换不成功
        guard let vc = classT as? UIViewController.Type else {return nil}
        return vc.init()
    }
    
    /// 字符串转date
    func stringDate() -> Date {
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        if let date = dateFormatter.date(from: self) {
            return date
        }
        return Date.init(timeIntervalSinceNow: 0)
    }
    
    /// check string cellection is whiteSpace
    var isBlank : Bool{
        return allSatisfy({$0.isWhitespace || $0.isNewline})
    }
    /// 字符串转富文本
    func gl_toAttribute() -> NSMutableAttributedString {
        return NSMutableAttributedString(string: self)
    }

    func filter(_ str: String) -> String {
        return self.replacingOccurrences(of: str, with: "", options: .literal, range: nil)
    }
}
